{% extends "admin/layout.html" %}
{% set active_page = 'groups' %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="mb-0"><i class="fas fa-plus-circle me-2 text-primary"></i>创建新群组</h3>
    <a href="{{ url_for('wxwork.group_management') }}" class="btn btn-outline-secondary">
        <i class="fas fa-arrow-left me-2"></i>返回列表
    </a>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-4">
        <form method="POST" action="{{ url_for('wxwork.create_group') }}">
            <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">

            <!-- 群名称 -->
            <div class="mb-4">
                <label class="form-label fw-medium">群名称 <span class="text-danger">*</span></label>
                <div class="input-group">
                    <span class="input-group-text bg-light"><i class="fas fa-edit"></i></span>
                    <input type="text"
                           class="form-control form-control-lg"
                           name="name"
                           placeholder="请输入群组名称"
                           required>
                </div>
            </div>

            <!-- 群主选择 -->
            <div class="mb-4">
                <label class="form-label fw-medium">群主 <span class="text-danger">*</span></label>
                <div class="position-relative">
                    <input type="text"
                           class="form-control form-control-lg"
                           list="ownerList"
                           id="ownerInput"
                           placeholder="输入姓名或工号搜索"
                           required
                           style="padding-right: 40px;">
                    <i class="fas fa-search text-muted position-absolute end-0 me-3"
                       style="top: 50%; transform: translateY(-50%);"></i>
                    <datalist id="ownerList">
                        {% for user in users %}
                        <option data-id="{{ user.id }}" value="{{ user.name }} ({{ user.wecom_userid }})">
                            {% endfor %}
                    </datalist>
                    <input type="hidden" name="owner_id" id="selectedOwner" required>
                </div>
            </div>

            <!-- 群成员选择 -->
            <div class="mb-4">
                <label class="form-label fw-medium d-flex justify-content-between">
                    <span>群成员</span>
                    <span class="badge bg-primary rounded-pill">
                        已选 <span id="selectedCount">0</span> 人
                    </span>
                </label>

                <!-- 已选成员标签 -->
                <div class="border rounded p-3 mb-2 bg-light member-tags-container">
                    <div class="text-muted text-center py-2" id="emptyHint">
                        <i class="fas fa-info-circle me-2"></i>暂无选中的成员
                    </div>
                </div>

                <!-- 成员搜索 -->
                <div class="input-group mb-2">
                    <span class="input-group-text bg-light"><i class="fas fa-search"></i></span>
                    <input type="text"
                           class="form-control"
                           placeholder="输入姓名或工号搜索"
                           oninput="filterMembers(this.value)">
                </div>

                <!-- 成员列表 -->
                <div class="border rounded member-list" style="max-height: 300px; overflow-y: auto;">
                    <div class="p-2 bg-light small text-muted sticky-top top-0">
                        <i class="fas fa-users me-2"></i>全公司成员（共 {{ users|length }} 人）
                    </div>
                    {% for user in users %}
                    <div class="form-check member-item p-3 border-bottom hover-bg"
                         data-id="{{ user.id }}"
                         style="transition: background 0.2s;">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <input class="form-check-input me-2"
                                       type="checkbox"
                                       name="user_ids"
                                       value="{{ user.id }}"
                                       id="user-{{ user.id }}">
                                <label class="form-check-label" for="user-{{ user.id }}">
                                    <span class="fw-medium">{{ user.name }}</span>
                                    <span class="text-muted ms-2">({{ user.wecom_userid }})</span>
                                    <div class="text-muted small">
                                        <i class="fas fa-building me-1"></i>{{ user.department_name }}
                                        {% if user.position %}
                                        <span class="ms-2"><i class="fas fa-briefcase me-1"></i>{{ user.position }}</span>
                                        {% endif %}
                                    </div>
                                </label>
                            </div>
                            <div class="text-muted small">
                                <i class="fas fa-mobile-alt me-1"></i>{{ user.mobile|default('未登记') }}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                <button type="reset" class="btn btn-lg btn-outline-secondary px-4">
                    <i class="fas fa-eraser me-2"></i>重置表单
                </button>
                <button type="submit" class="btn btn-lg btn-primary px-4">
                    <i class="fas fa-check-circle me-2"></i>立即创建
                </button>
            </div>
        </form>
    </div>
</div>

<style>
    /* 新增样式 */
    .hover-bg:hover {
        background: #f8f9fa !important;
    }

    .member-tag {
        display: inline-flex;
        align-items: center;
        padding: 0.35em 0.65em;
        font-size: 0.9em;
    }

    .member-tag i {
        transition: transform 0.2s;
    }

    .member-tag i:hover {
        transform: scale(1.1);
        color: #dc3545 !important;
    }

    .member-list::-webkit-scrollbar {
        width: 6px;
    }

    .member-list::-webkit-scrollbar-thumb {
        background: #dee2e6;
        border-radius: 4px;
    }
</style>
<script>
    // 新增群主选择逻辑
    document.getElementById('ownerInput').addEventListener('input', function(e) {
        const inputVal = e.target.value.trim();
        const options = document.querySelectorAll('#ownerList option');

        // 精确匹配已存在的选项
        const matchedOption = Array.from(options).find(option =>
            option.value.toLowerCase() === inputVal.toLowerCase()
        );

        if (matchedOption) {
            document.getElementById('selectedOwner').value = matchedOption.dataset.id;
        } else {
            document.getElementById('selectedOwner').value = '';
        }
    });

    // 添加表单提交验证
    document.querySelector('form').addEventListener('submit', function(e) {
        const ownerId = document.getElementById('selectedOwner').value;
        if (!ownerId) {
            e.preventDefault();
            alert('请从列表中选择有效的群主');
            return false;
        }
    });
</script>
<script>
    // 增强版成员选择逻辑
    let selectedMembers = new Set();

    // 更新已选人数
    function updateSelectedCount() {
        document.getElementById('selectedCount').textContent = selectedMembers.size;
        document.getElementById('emptyHint').style.display =
            selectedMembers.size > 0 ? 'none' : 'block';
    }

    // 成员选择交互
    document.querySelectorAll('.member-item input').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const memberId = this.value;
            const memberInfo = this.nextElementSibling.textContent.trim();

            if (this.checked) {
                selectedMembers.add(memberId);
                addMemberTag(memberId, memberInfo);
            } else {
                selectedMembers.delete(memberId);
                removeMemberTag(memberId);
            }
            updateSelectedCount();
        });
    });

    // 增强标签显示
    function addMemberTag(id, text) {
        const container = document.querySelector('.member-tags-container');
        if (!container.querySelector(`[data-id="${id}"]`)) {
            const tag = document.createElement('span');
            tag.className = 'badge bg-primary member-tag me-2 mb-2';
            tag.setAttribute('data-id', id);
            tag.innerHTML = `
            <span class="text-truncate" style="max-width: 150px;">${text}</span>
            <i class="fas fa-times ms-2 cursor-pointer"
               onclick="removeMemberTag('${id}')"></i>
        `;
            container.appendChild(tag);
        }
    }

    // 增强过滤功能
    function filterMembers(keyword) {
        const items = document.querySelectorAll('.member-item');
        items.forEach(item => {
            const text = item.querySelector('.form-check-label').textContent.toLowerCase();
            const show = text.includes(keyword.toLowerCase());
            item.style.display = show ? '' : 'none';
            item.style.backgroundColor = show ? '' : 'transparent';
        });
    }

    // 初始化计数
    updateSelectedCount();
</script>
{% endblock %}